###### @Author : WYK LastEditTime : 2021-10-22 10:46:28

######
#' @TODO 高低风险组免疫浸润分析
#' @title ## 高低风险组免疫浸润分析
#' @param estimate_res R包IOBR 计算结果
#' @param saveplot 是否保存图片
#' @param output_dir 文件保存路径，需要以`/`结尾
#' @param var_name  字符串，用来命名文件
#' @param risk_infor KM_ROC_curve计算结果第三个。或者一个包含`sample`与`riskscore`，`riskgroup`的*data.frame*
#' 
#' @param return_file 
#' 
#' @author *WYK*
######
Estimate_plot <- function(estimate_res = NULL, risk_infor = NULL, saveplot = F, var_name = NULL,
    output_dir = "./") {
    library(tidyverse)
    library(ggpubr)
    library(cowplot)

    if (is.null(var_name)) {
        var_name <- paste0("_", paste0(sample(letters, 4), collapse = ""))
    }

    p_estimate_data <- estimate_res %>%
        as.data.frame() %>%
        rename(sample = 1) %>%
        pivot_longer(cols = -sample, names_to = "cell_name", values_to = "score") %>%
        inner_join(., risk_infor)

    p_estimate <- p_estimate_data %>%
        ggboxplot(x = "riskgroup", y = "score", fill = "riskgroup", width = 0.5,
            outlier.size = 0.5) + xlab("Score") + ylab("") + stat_compare_means() +
        theme_bw() + theme(legend.position = "none", panel.grid = element_blank(),
        legend.title = element_blank()) + facet_wrap(~cell_name, nrow = 1, scales = "free") +
        scale_fill_manual(values = c(Low = "#377EB8", High = "#E41A1C")) + theme(axis.text = element_text(size = 12),
        plot.margin = unit(c(0.2, 0.2, 0.2, 0.2), "cm"))

    if (saveplot) {
        if (!dir.exists(sprintf("%s", output_dir))) {
            dir.create(sprintf("%s", output_dir))
        }

        dir_used <- sprintf("%s", output_dir)

        ggsave2(filename = sprintf("%sFigure_estimate%s.pdf", dir_used, var_name),
            plot = p_estimate, width = 9.2, height = 3.7)
    }

    return(p_estimate)
}

# (ns: p > 0.05，*: p <= 0.05，**: p <= 0.01， ***: p <= 0.001，****: p <=
# 0.0001)
